"use strict";
const semver = require("semver");
const colors = require("colors/safe");
// START 本地依赖库
const log = require("@wenjun-cli/log");
const { isObject } = require("@wenjun-cli/utils");
// 本地全局变量
const LOWEST_NODE_VERSION = "12.0.1";
class Command {
  constructor(argv) {
    // 构造函数
    // 对命令参数进行容错判断
    if (!argv) {
      throw new Error("argv参数不能为空！");
    }
    if (!Array.isArray(argv)) {
      throw new Error("参数必须是一个数组！");
    }
    if (argv.length < 1) {
      throw new Error("参数列表长度不能为空！");
    }
    this._argv = argv;
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      chain = chain.then(() => this.checkNodeVersion());
      chain = chain.then(() => this.initArgs());
      chain = chain.then(() => this.init());
      chain = chain.then(() => this.exec());
      chain.catch((err) => {
        log.error(err.message);
      });
    });
  }
  // init函数
  init() {
    throw new Error("init必须实现！");
  }
  // exec 函数
  exec() {
    throw new Error("exec必须实现！");
  }
  // 检查node版本
  checkNodeVersion() {
    // 第一步：获取当前的node版本号
    log.info("node", process.version);
    // 第二步：比对最低版本号
    const currentVersion = process.version;
    const lowestVersion = LOWEST_NODE_VERSION;
    if (!semver.gt(currentVersion, lowestVersion)) {
      throw new Error(
        colors.red(`wenjun-cli需要安装v${lowestVersion}以上版本的node.js`)
      );
    }
  }
  // 参数初始化操作
  initArgs() {
    log.info("args", "开始初始化参数......");
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
  }
}

module.exports = Command;
